package com.mbuswidget;

import java.util.ArrayList;
import java.util.Collections;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.util.Log;

public class MBusInfo {
	private final Integer numOfRoutes;
	private final ArrayList<BusRoute> routes;
	static private final String routeCountStr = "routecount";
	private ArrayList<String> allStopNames;
	private Context context;
	
	public MBusInfo(MBusInfo parent){
		numOfRoutes = parent.numOfRoutes;
		routes = new ArrayList<BusRoute>();
		context = parent.context;
		for (int x = 0; x < parent.routes.size(); x++)
			routes.add(new BusRoute(parent.routes.get(x)));
		Collections.sort(routes);
	}
	
	public MBusInfo(Document xmlDocument, Context context){
		Element xmlElement = xmlDocument.getDocumentElement();
		Element liveFeed = (Element)xmlElement.getElementsByTagName("livefeed").item(0);
		numOfRoutes = Integer.parseInt(Utils.getTextValue(liveFeed, routeCountStr));
		routes = new ArrayList<BusRoute>();
		allStopNames = null;
		NodeList routeList = liveFeed.getElementsByTagName("route");
		for (int x = 0; x < routeList.getLength(); x++)
			routes.add(new BusRoute((Element)routeList.item(x), context));
		Collections.sort(routes);		
	}
	
	public ArrayList<BusRoute> getRoutes(){
		return routes;
	}
	
	public BusRoute getRouteWithId(int id){
		for (BusRoute route : routes)
			if (route.getId() == id) return route;
		return null;
	}
	
	public BusRoute getRouteWithName(String routeName){
		for (BusRoute route : routes)
			if (route.getName().equals(routeName)) return route;
		return null;
	}
	
	public ArrayList<Pair<BusRoute, BusStop>> getRouteAndStopInfoForStopWithName(String stopName){
		ArrayList<Pair<BusRoute, BusStop>> stops = new ArrayList<Pair<BusRoute, BusStop> >();
		for (BusRoute route : routes){
			BusStop stop = route.getStopWithName(stopName);
			if (stop != null) stops.add(new Pair<BusRoute, BusStop>(route, stop));
		}
		return stops;
	}
	
	public ArrayList<String> getStopNamesAll(){
		if(allStopNames != null) return allStopNames;
		allStopNames = new ArrayList<String>();
		for (BusRoute route : routes) {
			for (BusStop stop : route.getStops()) {
				int indexToInsert = Collections.binarySearch(allStopNames, stop.getShortName());
				if(indexToInsert < 0) {
					allStopNames.add(-indexToInsert - 1, stop.getShortName());
				}
			}
		}
		
		return allStopNames;
	}
}